package com.example.book.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.book.model.Book;
import com.example.book.repository.BookList;

/**
 * Servlet implementation class BookCatalogServlet
 */
@WebServlet("/catalog")
public class BookCatalogServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		BookList bl = new BookList();
		List<Book> bookList = bl.getBooks();

		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		
		out.println("<html>");
		out.println(" <body>");
		Cookie username = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ("username".equals(cookie.getName())) {
					username = cookie;
					break;
				}
			}
		}
		
		if(username!=null){
			out.println("Welcome back "+"<b>"+username.getValue()+"<b>");
			out.println("<br>");
		}
		
		
		for (Book book : bookList) {
			String isbn = book.getIsbn();
			String title = book.getTitle();
			out.println("<a href='http://localhost:8080/BBStore/detail?isbn="
					+ isbn + "'>" + title + "</a>");
			out.println("<br>");

		}
		
		out.println(" </body>");
		out.println("</html>");
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
